package com.example.demo.service.impl;

import com.example.demo.config.WechatConfig;
import com.example.demo.model.dto.WechatSubscribeMessageDTO;
import com.example.demo.service.WechatService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class WechatServiceImpl implements WechatService {
    private final RestTemplate restTemplate;
    private final WechatConfig wechatConfig;

    private static final String SUBSCRIBE_MSG_SEND_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    public WechatServiceImpl(RestTemplate restTemplate, WechatConfig wechatConfig) {
        this.restTemplate = restTemplate;
        this.wechatConfig = wechatConfig;
    }

    @Override
    public String sendSubscribeMessage(WechatSubscribeMessageDTO messageDTO) {
        String accessToken = getAccessToken();
        String url = String.format("%s?access_token=%s", SUBSCRIBE_MSG_SEND_URL, accessToken);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<WechatSubscribeMessageDTO> request = new HttpEntity<>(messageDTO, headers);

        try {
            String response = restTemplate.postForObject(url, request, String.class);
            log.info("发送微信订阅消息成功: {}", response);
            return response;
        } catch (Exception e) {
            log.error("发送微信订阅消息失败: {}", e.getMessage(), e);
            throw new RuntimeException("发送微信订阅消息失败", e);
        }
    }

    @Override
    public String getAccessToken() {
        String url = String.format("%s?grant_type=client_credential&appid=%s&secret=%s",
                ACCESS_TOKEN_URL, wechatConfig.getAppId(), wechatConfig.getAppSecret());

        try {
            String response = restTemplate.getForObject(url, String.class);
            log.info("获取微信access_token响应数据: {}", response);
            // 使用 Jackson 或其他 JSON 处理库解析响应
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(response);
            return node.get("access_token").asText();
        } catch (Exception e) {
            log.error("获取微信access_token失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取微信access_token失败", e);
        }
    }
}
